package com.peanut.web.controller.yeebao;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.peanut.service.pay.IPayService;
import com.peanut.service.pay.data.PayRegisterParam;
import com.peanut.service.pay.data.PayResponse;
import com.peanut.service.pay.data.PayEnum.PayChannel;
import com.peanut.service.pay.data.PayEnum.PaySide;
import com.peanut.service.pay.data.yeebao.YeeBaoClientCallBackParam;
import com.peanut.service.pay.data.yeebao.YeeBaoServerCallBackParam;
import com.peanut.util.operation.OperationResult;
import com.peanut.util.pay.PayCallbackUtil;

/**
 * 易宝注册controller
 * 
 * @author jzsong@uworks.cc
 */
@Api(value = "易宝注册管理", produces = "application/json")
@Controller
@RequestMapping(value = "/yeebaoregister")
public class YeeBaoRegisterController extends YeeBaoBaseController {
  private Logger logger = LoggerFactory.getLogger(getClass());

  @Resource
  private IPayService payService;

  /**
   * <pre>
   * 用户注册
   * 请求方式:POST，请求路径:/yeebaoregister/register
   * 请求参数：
   *          realName      用户真实的姓名
   *          idCardNo      用户真实的身份证号
   * 返回数据：
   *     redirectUrl       重定向url
   *     redirectMethod    重定向-请求方式，POST、GET
   *     redirectParameter 重定向-请求参数（json数组，key为请求的name，value：请求的值）
   * </pre>
   * 
   * @param realName
   * @param idCardNo
   * @param request
   * @return
   */
  @ApiOperation(value = "第三方易宝注册", notes = "", httpMethod = "POST", produces = "application/json")
  @RequestMapping(value = "/register", method = { RequestMethod.POST })
  @ResponseBody
  public String register(@RequestParam(value = "realName") String realName,
      @RequestParam(value = "idCardNo") String idCardNo, HttpServletRequest request) {
    logger.info(LABEL + "-注册开始...");
    Long userId = getCurrentUserId(request);
    PayRegisterParam p = new PayRegisterParam(userId, PaySide.MOBILE);
    p.setPayChannel(PayChannel.YEEBAO);
    p.setRealName(realName);
    p.setIdCardNo(idCardNo);
    p.setClientCallbackUrl(PayCallbackUtil.registerClient(p.getPayChannel(), p.getPaySide()));
    p.setServerCallbackUrl(PayCallbackUtil.registerServer(p.getPayChannel(), p.getPaySide()));
    PayResponse payResponse = payService.register(p);
    logger.info(LABEL + "-注册处理结果：" + JSON.toJSONString(payResponse));
    if (payResponse.isSuccess()) {
      return OperationResult.success(payResponse);
    }
    return OperationResult.fail(payResponse.getMessage());
  }

  /**
   * <pre>
   * 用户注册前台回调
   * 请求方式:POST，请求路径:/yeebaoregister/clientCallback
   * 请求参数：
   *          notify  xml数据
   *          sign    签名
   * 返回数据：
   *          page/clientCallBack.jsp
   * </pre>
   * 
   * @param request
   * @return
   * @throws Exception
   */
  @ApiOperation(value = "易宝注册前台回调", notes = "", httpMethod = "POST", produces = "application/html")
  @RequestMapping(value = "/clientCallback", method = { RequestMethod.POST })
  public String clientCallback(HttpServletRequest request) {
    logger.info(LABEL + "-注册前台回调开始...");
    String result = OperationResult.RESULT.FAIL.toString();
    String message = "";
    try {
      YeeBaoClientCallBackParam param = buildClientCallBackParam(request);
      PayResponse payResponse = payService.registerClientCallBack(param);
      logger.info(LABEL + "-注册前台回调处理结果：" + JSON.toJSONString(payResponse));
      if (!payResponse.isSuccess()) {
        message = payResponse.getMessage();
      } else {
        result = OperationResult.RESULT.SUCCESS.toString();
      }
    } catch (Exception e) {
      logger.info("", e);
      message = "系统发生错误";
    }
    request.setAttribute("message", message);
    request.setAttribute("result", result);
    return CLIENT_PAGE;
  }

  /**
   * <pre>
   * 用户注册后台回调
   * 请求方式:POST，请求路径:/yeebaoregister/serverCallback
   * 请求参数：
   *          notify  xml数据
   *          sign    签名
   * 返回数据：
   *          SUCCESS
   * </pre>
   * 
   * @param request
   * @return
   * @throws Exception
   */
  @ApiOperation(value = "易宝注册后台回调", notes = "", httpMethod = "POST", produces = "application/json")
  @RequestMapping(value = "/serverCallback", method = { RequestMethod.POST })
  @ResponseBody
  public String serverCallback(HttpServletRequest request) {
    logger.info(LABEL + "-注册后台回调开始...");
    try {
      YeeBaoServerCallBackParam param = buildServerCallBackParam(request);
      PayResponse payResponse = payService.registerServerCallBack(param);
      logger.info(LABEL + "-注册后台回调处理结果：" + JSON.toJSONString(payResponse));
    } catch (Exception e) {
      logger.info("", e);
    }
    return SUCCESS;
  }

}
